
// 请求导出项目列表数据
import saleApi from "@/api/saleApi";
export function exportSaleProjectExcel(field_list, formSearch, page, num) {
    return new Promise((resolve, reject) => {
        saleApi.exportSaleProjectExcel({
            field_list,
            brand_id: formSearch.brand_id || '',
            store_type_id: formSearch.store_type_id || '',
            project_name: formSearch.project_name || '',
            project_number: formSearch.project_number || '',
            display_status: formSearch.display_status || '',
            // created_at: formSearch.created_at,
            province_id: formSearch.city ? formSearch.city[0] : '',
            city_id: formSearch.city ? formSearch.city[1] : '',
            county_id: formSearch.city ? formSearch.city[2] : '',
            created_at_start: formSearch.created_at ? formSearch.created_at[0] : '',
            created_at_end: formSearch.created_at ? formSearch.created_at[1] : '',
            overall_rating: formSearch.overall_rating || '',
            account_manager_id: formSearch.account_manager_id || '',
            engineering_manager_id: formSearch.engineering_manager_id || '',
            engineering_supervision_id: formSearch.engineering_supervision_id || '',
            user_name: formSearch.user_name || '',
            contract_commencement_date_start: formSearch.contract_commencement_date ? formSearch.contract_commencement_date[0] : '',
            contract_commencement_date_end: formSearch.contract_commencement_date ? formSearch.contract_commencement_date[1] : '',
            contract_completion_date_start: formSearch.contract_completion_date ? formSearch.contract_completion_date[0] : '',
            contract_completion_date_end: formSearch.contract_completion_date ? formSearch.contract_completion_date[1] : '',
            construction_status: formSearch.construction_status || '',
            acceptance_progress: formSearch.acceptance_progress || '',
            risk_label: formSearch.risk_label || "",
            settlement_completion_date_start: formSearch.settlement_completion_date ? formSearch.settlement_completion_date[0] : '',
            settlement_completion_date_end: formSearch.settlement_completion_date ? formSearch.settlement_completion_date[1] : '',
            warranty_deadline_date_start: formSearch.warranty_deadline_date ? formSearch.warranty_deadline_date[0] : '',
            warranty_deadline_date_end: formSearch.warranty_deadline_date ? formSearch.warranty_deadline_date[1] : '',
            page,
            num
        }).then(res => {
            console.log(res, "导出销售项目列表")
            if (res.code == 200) {
                let headers = [
                    // { key: 'id', text: 'ID', width: 10 },
                ]
                let obj = res.data[0][0] || {};
                let nameArr = res.data[1];
                const keyArr = Object.keys(obj);
                nameArr.forEach((item, index) => {
                    headers.push({
                        key: keyArr[index], text: item, width: 10
                    })
                })
                resolve({
                    list: res.data[0],
                    headers
                })
            } else {
                resolve(false);
            }
        }).catch(err => {
            resolve(false);
        })
    })
}


// 导出excel
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'
import { Message } from 'element-ui'
export function exportToExcel(tableData, headers) {
    // console.log(tableData, headers, "tableData, headers")
    if (!headers.length || !tableData.length) {
        Message.warning(`导出Excel失败:No data to export`)
        return;
    }
    return new Promise(async (resolve, reject) => {
        try {
            // 创建工作簿
            const workbook = new ExcelJS.Workbook()

            // 添加工作表
            const worksheet = workbook.addWorksheet('项目列表')

            // 设置表头样式
            const headerRow = worksheet.addRow(headers.map(h => h.text))
            headerRow.font = {
                name: '微软雅黑',
                bold: true,
                size: 12,
                color: { argb: 'FFFFFFFF' }
            }
            headerRow.fill = {
                type: 'pattern',
                pattern: 'solid',
                fgColor: { argb: 'FF4F81BD' }
            }
            headerRow.alignment = {
                vertical: 'middle',
                horizontal: 'center'
            }

            // 设置列宽
            worksheet.columns = headers.map(header => ({
                width: header.width
            }))

            // 添加数据行
            tableData.forEach(item => {
                const dataRow = worksheet.addRow(headers.map(header => item[header.key]))
                dataRow.font = {
                    name: '微软雅黑',
                    size: 11
                }
                dataRow.alignment = {
                    vertical: 'middle',
                    horizontal: 'left'
                }
            })

            // 添加边框
            worksheet.eachRow((row, rowNumber) => {
                row.eachCell(cell => {
                    cell.border = {
                        top: { style: 'thin' },
                        left: { style: 'thin' },
                        bottom: { style: 'thin' },
                        right: { style: 'thin' }
                    }
                })
            })

            // 生成文件并下载
            const buffer = await workbook.xlsx.writeBuffer()
            resolve();
            const blob = new Blob([buffer], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            // 创建Date对象
            const date = new Date();
            // 获取年份（4位）
            const year = date.getFullYear();
            // 获取月份（0-11，需要+1）
            const month = date.getMonth() + 1;
            // 获取日期（1-31）
            const day = date.getDate();
            saveAs(blob, `项目列表${year}-${month}-${day}.xlsx`)
        } catch (error) {
            console.error('导出Excel失败:', error)
            Message.warning(`导出Excel失败:${error}`)
            resolve();
        }
    })
}


export function generateDetail(timeObj) {
    timeObj = parseInt(timeObj) || 0;
    const hours = Math.floor(timeObj / 3600);
    const minutes = Math.floor((timeObj % 3600) / 60);
    const seconds = timeObj % 60;
    if (hours > 0) {
        return `${hours}小时${minutes}分${seconds}秒`;
    } else if (minutes > 0) {
        return `${minutes}分${seconds}秒`;
    } else {
        if (seconds == 0) return '即将完成，请稍等...'
        return `${seconds}秒`;
    }
}